package com.demo.wxconfig.demos.web.service.imp;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.demo.wxconfig.demos.web.config.WxConfig;
import com.demo.wxconfig.demos.web.constants.WxUrlPathConstant;
import com.demo.wxconfig.demos.web.dto.AccessToken;
import com.demo.wxconfig.demos.web.dto.JsapiTicket;
import com.demo.wxconfig.demos.web.dto.WXEntity;
import com.demo.wxconfig.demos.web.service.WxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class WxServiceImpl implements WxService {

    @Autowired
    private WxConfig wxConfig;

    @Override
    public String getAccessToken() {
        String resp = HttpUtil.get(String.format(WxUrlPathConstant.ACCESS_TOKEN, wxConfig.getAppId(), wxConfig.getAppSecret()));
        AccessToken accessToken = JSON.parseObject(resp, AccessToken.class);
        return accessToken.getAccessToken();
    }

    @Override
    public String getJsapiTicket() {
        String resp = HttpUtil.get(String.format(WxUrlPathConstant.JSAPI_TICKET, getAccessToken()));
        JsapiTicket jsapiTicket = JSON.parseObject(resp, JsapiTicket.class);
        return jsapiTicket.getTicket();
    }

    @Override
    public WXEntity getWxConfig(String url) {
        WXEntity wxEntity = new WXEntity();
        wxEntity.setAppId(wxConfig.getAppId());
        //获取时间戳
        String timestamp = getTimestamp();
        wxEntity.setTimestamp(timestamp);
        //获取随机数
        String nonceStr = getNoncestr();
        wxEntity.setNonceStr(nonceStr);
        //获取jsapi_ticket码
        String ticket = getJsapiTicket();
        //获取网页连接
        wxEntity.setUrl(url);
        //拼接
        String str = sort(url,timestamp,ticket,nonceStr);
        //获取密钥
        String signature = sha1(str);
        wxEntity.setSignature(signature);
        return wxEntity;
    }


    /**获取随机数*/
    public static String getNoncestr(){
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
    /**获取时间戳*/
    public static String getTimestamp(){
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 排序
     * @param url url
     * @param timestamp 时间戳
     * @param ticket 临时凭证
     * @param noncestr
     * @return
     */
    public static String sort(String url, String timestamp, String ticket, String noncestr) {
        return "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
    }

    /**
     * @Param [str]
     * @Return java.lang.String
     * @Description: 将字符串进行sha1加密
     */
    public static String sha1(String str){
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte[] messageDigest = digest.digest();
            // 创建 16进制字符串
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


}
